package com.xbjtech.shiro.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.mapper.UserRoleMapper;
import com.xbjtech.model.Permission;
import com.xbjtech.model.Role;
import com.xbjtech.model.User;
import com.xbjtech.service.PermissionService;
import com.xbjtech.service.RoleService;
import com.xbjtech.service.UserService;

public class CustomRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;
	
	@Autowired
	RoleService roleService;
	
	@Autowired
	PermissionService permissionService;
	
	/**
	 * shiro认证方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		if (!(token instanceof UsernamePasswordToken)) {
			throw new AuthenticationException("登陆失败");
		}
		UsernamePasswordToken t = (UsernamePasswordToken) token;
		String username = t.getUsername();
		
		User user = userService.selectUserByUsername(username);
		if (user == null || user.getDeleted().compareTo(1) == 0) {
			throw new UnknownAccountException("用户名不存在");
		}
		if (user.getLocked().compareTo(1) == 0) {
			throw new LockedAccountException("用户名已锁定");
		}
		ByteSource salt = ByteSource.Util.bytes(user.getId() + "");
		return new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName());
	}
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		List<Role> roles = roleService.selectRolesByUserId(user.getId());
		for (Role r : roles) {
			info.addRole(r.getDescript());
		}

		List<Permission> permissions = permissionService.selectPermissionsByUserId(user.getId());
		for (Permission p : permissions) {
			info.addStringPermission(p.getParam());
		}
//		info.addStringPermission("order:list");
//		info.addStringPermission("order:pdlist");
		return info;
	}

	
	public static void main(String[] args) {
		SimpleHash simpleHash = new SimpleHash("MD5", "123456", ByteSource.Util.bytes("2"), 1);
		System.out.println(simpleHash);
	}
	
	
}
